import 'dart:io';
import 'dart:typed_data';

class AudioUtil {


  static Future<void> pcmToWav({
    required String pcmPath,
    required String wavPath,
    required int sampleRate,
    required int bitDepth,
    required int channels,
  }) async {
    final pcmFile = File(pcmPath);
    final pcmBytes = await pcmFile.readAsBytes();
    final header = _buildWavHeader(
      pcmDataLength: pcmBytes.length,
      sampleRate: sampleRate,
      bitDepth: bitDepth,
      channels: channels,
    );

    final wavFile = await File(wavPath).writeAsBytes(header + pcmBytes,flush: true);

    print('wavFile size: ${await wavFile.length()}');


  }

  static Uint8List _buildWavHeader({
    required int pcmDataLength,
    required int sampleRate,
    required int bitDepth,
    required int channels,
  }) {
    final byteRate = sampleRate * channels * bitDepth ~/ 8;
    final blockAlign = channels * bitDepth ~/ 8;
    final dataLength = pcmDataLength;
    final totalLength = dataLength + 36; // 文件总长度 = data长度 + 36字节头信息

    final header = ByteData(44)
      ..setUint32(0, 0x46464952, Endian.little)  // "RIFF"
      ..setUint32(4, totalLength, Endian.little)
      ..setUint32(8, 0x45564157, Endian.little)  // "WAVE"
      ..setUint32(12, 0x20746d66, Endian.little) // "fmt "
      ..setUint32(16, 16, Endian.little)         // fmt块长度固定16
      ..setUint16(20, 1, Endian.little)          // PCM格式编码类型
      ..setUint16(22, channels, Endian.little)
      ..setUint32(24, sampleRate, Endian.little)
      ..setUint32(28, byteRate, Endian.little)
      ..setUint16(32, blockAlign, Endian.little)
      ..setUint16(34, bitDepth, Endian.little)
      ..setUint32(36, 0x61746164, Endian.little) // "data"
      ..setUint32(40, dataLength, Endian.little);

    return header.buffer.asUint8List();
  }
}